<template>
  <div class="xqjhAdd">
    <span class="borderNone">
      <p class="shenqing">已添加物料</p>
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        style="margin-left: 15px"
        :rules="rules"
      >
        <el-form-item label="申请名称" >
          <el-input v-model="queryParams.pickName" placeholder="请输入申请名" clearable size="small" />
        </el-form-item>
        <el-form-item label="用途">
          <el-input v-model="queryParams.useing" placeholder="请输入用途" clearable size="small" />
        </el-form-item>
        <el-form-item label="计划月份" prop="planMonth">
          <el-date-picker
            v-model="queryParams.planMonth"
            type="month"
            size="small"
            format="yyyy-MM"
            value-format="yyyy-MM"
            placeholder="选择月"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="计划类型">
          <el-select v-model="queryParams.planType" placeholder="请选择" clearable size="small">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="资金来源" prop="moneySource">
          <el-select v-model="queryParams.moneySource" placeholder="请选择" clearable size="small">
            <el-option
              v-for="dict in zjlyList"
              :key="dict.id"
              :label="dict.cpName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="queryParams.note"
            placeholder="请输入备注"
            clearable
            size="small"
          />
        </el-form-item>
      </el-form>
      <div style="margin-left: 15px;margin-bottom: 15px">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="choose">选择</el-button>
        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteBtn">删除</el-button>
        <el-button
          :loading="loading"
          type="success"
          icon="el-icon-plus"
          size="mini"
          @click="tijiao"
        >保存</el-button>
        <el-button type="success" size="mini" icon="el-icon-plus" @click="addWl">新增物料信息</el-button>
        <el-button type="success" size="mini" icon="el-icon-plus" @click="drhistoryXQ">导入历史需求</el-button>
        <el-button type="primary" icon="el-icon-back" size="mini" @click="goback">返回上一页</el-button>
        <!-- <el-input
          type="number"
          placeholder="请输入查询的物料编码"
          style="width:30%;padding-left:10px;padding-top:20px"
          v-model="wlBianma"
        ></el-input>
        <el-button type="success" size="mini" icon="el-icon-search" @click="cxWlme">批量导入</el-button> -->
      </div>
      <el-table
        :data="tableDatajihua"
        stripe
        style="margin-left: 15px;width: 1526px"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column align="center" type="selection" width="80"></el-table-column>
        <el-table-column align="center" type="index" label="序号" width="55" />
        <el-table-column align="center" label="物料编码" property="mno" width="180" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column align="center" label="物料名称" property="mname" width="180"></el-table-column>
        <el-table-column align="center" label="物料规格" property="mmodel" width="180"></el-table-column>
        <el-table-column align="center" label="单位" property="unit" width="180"></el-table-column>
        <el-table-column align="center" label="计划价" property="planPrice" width="180"></el-table-column>
        <el-table-column
          align="center"
          label="技术参数"
          property="technicalParameters"
          :show-overflow-tooltip="true"
          v-if="false"
        ></el-table-column>
        <el-table-column align="center" label="需求数" property="demandNum" width="130">
          <template slot-scope="scope">
            <el-input
              type="number"
              v-model="scope.row.demandNum"
              placeholder
              :ref="'mark'+scope.$index"
              @input="xqNum(scope)"
              @keyup.enter.native='keyupBtn(scope)'
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="库存" property="inventory" width='180'></el-table-column>
        <el-table-column align="center" label="备注" property="note" width='180'>
          <template slot-scope="scope">
            <el-input
              type="text"
              v-model="scope.row.note"
              placeholder
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
      <!-- <div>
      <el-input type="text" placeholder="请输入查询的物料编码"
      style="width:30%;line-height:auto;margin-top:35px;margin-left:10px"
      v-model="wlBianma"
      @keyup.enter.native='cxdrWlme'
      ></el-input>
      <el-button type="success" size="mini" icon="el-icon-plus" @click="cxdrWlme">批量导入</el-button>
      </div> -->
      <!-- <div class="table">
        <el-table
        style="margin-left: 15px;width: 90%">
          <el-table-column align="center" type="index" label="" width="55" />
        <el-table-column align="center"   width="180" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column align="center" ></el-table-column>
        <el-table-column align="center"  ></el-table-column>
        <el-table-column align="center"  ></el-table-column>
        <el-table-column align="center"  ></el-table-column>
        <el-table-column
          align="center"
          label=""
          property="technicalParameters"
          :show-overflow-tooltip="true"
          v-if="false"
        ></el-table-column>
        <el-table-column align="center" label="" property="demandNum" width="130">
          <template slot-scope="scope">
            <el-input
              type="number"
              v-model="scope.row.demandNum"
              placeholder
              @input="keydownBtn(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="" property="inventory"></el-table-column>
        </el-table>
      </div> -->
    </span>
    <div style="margin-left: 15px;margin-bottom:300px;width: 90%;" class="inputme" >
      <input type="text" style='width:80px;background-color: #fff;' disabled="disabled">
      <input type="text" style='width:55px' disabled="disabled">
      <input type="text" style='width:180px;padding-left:10px' placeholder="请输入物料编码并回车" v-model="wlBianma" @keyup="cxwlMEssage">
      <input type="text" style='width:180px' disabled="disabled">
      <input type="text" style='width:180px' disabled="disabled">
      <input type="text" style='width:180px' disabled="disabled">
      <input type="text" style='width:180px' disabled="disabled">
      <input type="text" style='width:130px' disabled="disabled">
      <input type="text" style='width:180px' disabled="disabled">
      <input type="text" style='width:180px' disabled="disabled">
    </div>
    <wizuAdd-Dialog :addProductData="transmitData" v-if="addshow" @addProductBack="callback"></wizuAdd-Dialog>
    <add-Wl v-if="addwlShow" ref="tc" @callback="getXZwl(xzWLme)"></add-Wl>
    <history-XQ v-if="historyShow" ref='tt' @xqHistoryme='wlHistoryme'></history-XQ>
  </div>
</template>

<script>
import wizuAddDialog from "./wizuAddDialog";
import request from "@/utils/request";
import addWl from "../../suppliesLLGL/addWl";
import historyXQ from "../../suppliesLLGL/historyXQ";
export default {
  name: "Role",
  components: {
    wizuAddDialog,
    addWl,
    historyXQ,
  },
  data() {
    return {
       //页码信息
      XQpage:undefined,
      XQsize:undefined,
      loading: false,
      //新增物料显示
      addwlShow: false,
      //展示历史
      historyShow: false,
      //物料编码
      wlBianma: "",
      obj: {},
      //查询物料展示
      // cxWlme: false,
      //资金来源
      zjlyList: [],
      //鼠标聚焦的物料信息
      currentRow:null,
      statusOptions: [
        { value: 1, label: "月度计划" },
        { value: 2, label: "临时计划" },
      ],
      reportData: [],
      queryParams: {
        pickName: "",
        useing: "",
        planMonth: "",
        planType: "",
        note: "",
        moneySource: "",
      },
      defaultProps: {
        children: "childList",
        label: "wname",
      },
      bukedianji: false,
      // 表单校验
      rules: {
        moneySource: [
          { required: true, message: "资金来源不能为空", trigger: "blur" },
        ],
        planMonth: [
          { required: true, message: "计划月份不能为空", trigger: "blur" },
        ],
        // pickName: [
        //   { required: true, message: "申请名不能为空", trigger: "blur" },
        // ],
      },
      leixng: "post",
      addshow: false,
      transmitData: {}, //传给子集的数据
      shuliangSum: 0, //总数量
      jinesum: 0, //总金额
      tableDataxunz: "",
      dialogVisible: false,
      optionsleixing: [
        { value: "1", label: "设备采购" },
        { value: "2", label: "备件消耗材料采购" },
      ], //类型数据
      optionscgzq: [
        //采购周期
        { value: "1", label: "年" },
        { value: "2", label: "季" },
        { value: "3", label: "月" },
      ],
      //单位数据
      optionsdanwei: [
        { value: "1", label: "支" },
        { value: "2", label: "桶" },
        { value: "3", label: "箱" },
        { value: "4", label: "把" },
        { value: "5", label: "克" },
        { value: "6", label: "卷" },
      ],
      //总数居
      shenqingxinxi: {
        inputBiaoTi: "ceshi", //标题
        leixngXL: "1", //类型下拉
        cgzq: "1", //采购周期
        nianfen: "", //年份
        jidu: "", //季度
        beizhu: "", //备注
      },
      //采购信息
      caigouxinxi: {
        inputBiaoTi: "", //标题
        ghsj: "", //供货时间
        cgjh: "", //采购计划
        gouzhiliyou: "", //购置理由
        beizhu: "", //备注
      },
      tableDatajihua: [],
      tableDatajihuaXZ: [], //选中的数据
      //参数
      cData: this.$route.query.data,
      //详情id数据
      wlMessage: "",
      //详情id
      id: "",
    };
  },

  created() {
    console.log("接收参数", this.$route.query);
    var myDate = new Date();
    var yue = myDate.getMonth()+1
      if(yue<9){
        yue = '0'+yue
      }
    var ri = myDate.getDate()
    this.queryParams.pickName =  myDate.getFullYear()+'-'+ yue+'-'+ri+'-'+'需求申请单';
    console.log(this.queryParams.pickName)
    this.hejisum();
    this.getTreeselect();
    this.getZjly();
    this.id = this.$route.query.data.id;
    this.XQpage = this.$route.query.page
    this.XQsize = this.$route.query.size
    // console.log(this.id)
    console.log(this.cData);
    // debugger
    if (this.$route.query.data.id) {
      //修改
      this.getWlMessage();
      this.leixng = "put";
      this.queryParams.id = this.$route.query.data.id;
      this.queryParams.pickName = this.$route.query.data.pickName;
      this.queryParams.useing = this.$route.query.data.useing;
      this.queryParams.planMonth = this.$route.query.data.planMonth;
      this.queryParams.planType = this.$route.query.data.planType;
      this.queryParams.note = this.$route.query.data.note;
      this.queryParams.moneySource = this.$route.query.data.moneySource;
      // this.tableDatajihua =this.$route.query.data.wzDemandPlanInfos
      // console.log(123)
      // console.log(this.tableDatajihua)
      if (!this.tableDatajihua) {
        console.log('000')
        this.tableDatajihua = [];
      }
    }
  },
  methods: {
    //获取资金来源
    getZjly: function () {
      request({
        url: "/method/costproject/listByMydepId ",
        method: "get",
      }).then((response) => {
        this.zjlyList = response.rows;
        console.log("资金来源", this.zjlyList);
      });
    },
    // 展示导入需求
    drhistoryXQ() {
      this.historyShow = true;
      this.$refs.tt.dialogTableVisible = true;
    },
      //返回
      goback () {
         this.$router.push({path:'/material/mplan',query:{page:this.XQpage,size:this.XQsize}});
      },
    //新增物料
    addWl() {
      this.addwlShow = true;
      this.$refs.tc.dialogTableVisible = true;
    },
    //获取新增物料详细信息
    getXZwl(xzWLme) {
      console.log("新增信息" + xzWLme);
    },
    cxdrWlme () {
      // this.obj.mno = this.wlBianma
      // console.log(this.obj.mno)
      // var aa = this.xqJhid()
      // console.log(aa)
      // if(aa.indexOf(this.obj.mno)==-1) {
      //   request({
      //     url:'/material/supplies/listByno',
      //     method:'post',
      //     data:JSON.stringify(this.obj)
      //   }).then(response =>{
      //     console.log(response.data[0])
      //     this.tableDatajihua.push(response.data[0])
      //     console.log(this.tableDatajihua)
      //   })
      // }else {
      //   this.$notify({
      //     title: "警告",
      //     message: "请输入物料编码/重复",
      //     type: "warning",
      //   });
      //   console.log('编码重复')
      // }

      //批量导入的物料信息
      var plDRme = []
      this.obj.mno = this.wlBianma
      console.log(JSON.stringify(this.obj))
      request({
        url:'/material/supplies/listByno',
        method:'post',
        data:JSON.stringify(this.obj)
      }).then(response =>{
        console.log(response)
        this.wlBianma=''
        plDRme = response.data
        plDRme.forEach((item,index) =>{
          if(this.xqJhid().indexOf(item.mno)==-1) {
            this.tableDatajihua.push(plDRme[index])
          }
        })
      }).catch(e=>{
        console.log(e)
      })

    },
    // 需求计划id
    xqJhid () {
      let planid=[]
      this.tableDatajihua.forEach(item =>{
        planid.push(item.mno)
      })
      return planid
    },
    //导入的历史物料信息
    wlHistoryme (wlme) {
       console.log(456,wlme)
       const d = this.xqJhid()
       wlme.forEach((item,index) => {
         if(d.indexOf(item.mno)==-1) {
            this.tableDatajihua.push(wlme[index])
            // console.log('添加')
         }else {
          //  console.log('相同')
         }
       });
       console.log(this.tableDatajihua)
    },
    // 获取详细信息
    getWlMessage() {
      request({
        url: "/system/demandPlan/" + this.id,
        method: "get",
      }).then((response) => {
        this.tableDatajihua = response.data.wzDemandPlanInfos;
      })
    },
    // tjShuju (wlBianma) {
    //   this.wlBianma = wlBianma
    //   console.log(wlBianma)
    // },
    // search (wlBianma) {
    //    console.log(wlBianma)
    //    console.log(123)
    //    this.cxWlme = true
    // },

    //查询物料框回车事件
    cxwlMEssage (e) {
      if(e.keyCode=='13') {
        this.cxdrWlme()
      }else {
        return
      }
    },
    // 键盘按下事件
    keyupBtn: function (scope) {
      // debugger;
      if (scope.row.demandNum < 0) {
        scope.row.demandNum = 1;
      }
      // this.$refs.index.$index+1
      // this.$refs.index.$index+1
      // console.log(this.$refs.index)
      const len = this.tableDatajihua.length
      const val = this.currentRow.row
      console.log(val)
      this.tableDatajihua.forEach((item,index) =>{
        if(item===val) {
          if(index<len-1) {
            this.$refs['mark' + (index + 1)].focus()
          }else {
            this.$refs['mark' + (0)].focus()
          }
        }
      })
      console.log(scope.$index)
      console.log('键盘回车跳转下一行',scope.row)
    },
    //
    xqNum(val) {
      // if(val.row.demandNum>val.row.inventory) {
      //   val.row.demandNum = val.row.inventory
      // }
      if (val.row.demandNum < 0) {
        // val.row.demandNum = 0;
        this.$message({
          type:'info',
          message:'需求数不能为负数'
        })
      }
      // if(val.row.demandNum>val.row.inventory) {
      //   val.row.demandNum=val.row.inventory
      //   this.$message({
      //     type:'info',
      //     message:'需求数不能大于库存'
      //   })
      // }
       this.currentRow = val
       },
    handleNodeClickSJ: function (node) {
      console.log(node, "node");
      this.queryParams.waId = node.id;
      this.queryParams.wnameSJ = node.wname;
      this.$refs.selectReport.blur();
    },
    getTreeselect() {
      request({
        url: "/system/warehouse/listTree",
        method: "get",
      }).then((response) => {
        this.reportData = response.data;
      });
    },
    //弹框关闭回调函数
    callback: function (msg) {
      this.addshow = false;
      console.log("1111", msg);
      msg.forEach(item =>{
        if(item.demandNum==null) {
          item.demandNum=0
          // console.log(456)
        }
      }),
      this.tableDatajihua = this.deteleObject(this.tableDatajihua.concat(msg));
      msg.forEach((item,index) =>{
        if(this.xqJhid().indexOf(item.mno)==-1) {
          this.tableDatajihua.push(msg[index])
        }
      })
    },
    deteleObject: function (data) {
      let hash = {};
      const data2 = data.reduce((preVal, curVal) => {
        hash[curVal.mno]
          ? ""
          : (hash[curVal.mno] = true && preVal.push(curVal));
        return preVal;
      }, []);
      return data2;
    },
    //附件删除
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-3);
    },
    //表格复选框监听
    handleSelectionChange: function (row) {
      this.tableDatajihuaXZ = row;
      console.log(" this.tableDatajihuaXZ", this.tableDatajihuaXZ);
    },
    //类型监听
    leixingchange: function (row) {
      console.log("row", row);
    },

    //删除
    deleteBtn: function () {
      // debugger;
      for (var i = 0; i < this.tableDatajihua.length; i++) {
        for (var j = 0; j < this.tableDatajihuaXZ.length; j++) {
          if (this.tableDatajihua[i].id == this.tableDatajihuaXZ[j].id) {
            //相等
            this.tableDatajihua.splice(i, 1);
          }
        }
      }
      // if (this.tableDatajihua.length > 0) {
      //   this.bukedianji = true;
      // } else {
      //   this.bukedianji = false;
      // }
      this.fuzhiIndex();
    },
    //重新赋值index
    fuzhiIndex: function () {
      for (var i = 0; i < this.tableDatajihua.length; i++) {
        this.tableDatajihua[i].index = i;
      }
    },
    //选择
    choose: function () {
      this.addshow = true;
      var pp = {
        id: this.queryParams.waId,
      };
      this.transmitData = pp;
    },
    //产品表格监听
    chanpinonChange(val) {
      console.log(val);
    },
    //分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    //数量监听事件
    shulaingBtn: function (row) {
      console.log(row);
      row.xiaoji = row.cgsl * 1 * (row.jhje * 1);
      this.hejisum();
    },
    //单价监听事件
    yjdjBtn: function (row) {
      console.log(row);
      row.xiaoji = row.cgsl * 1 * (row.jhje * 1);
      this.hejisum();
    },
    //合计
    hejisum: function () {
      var shuchushi = 0;
      var jinechushi = 0;
      for (var i = 0; i < this.tableDatajihua.length; i++) {
        shuchushi = shuchushi + this.tableDatajihua[i].cgsl * 1;
        jinechushi = jinechushi + this.tableDatajihua[i].xiaoji * 1;
      }
      this.shuliangSum = shuchushi;
      this.jinesum = jinechushi;
    },
    tijiao: function () {
      // if (!this.queryParams.pickName) {
      //   this.$message({
      //     type: "error",
      //     message: "申请名不能为空",
      //   });
      //   return;
      // }
      if (!this.queryParams.planMonth) {
        this.$message({
          type: "error",
          message: "计划月份不能为空",
        });
        return;
      }
      if (!this.queryParams.moneySource) {
        this.$message({
          type: "error",
          message: "资金来源不能为空",
        });
        return;
      }
      debugger
      if(this.tableDatajihua.length==0){
        this.$message({
          type: "error",
          message: "申请数量不能为空",
        });
        return;
      }
      // if (this.tableDatajihua.length == 0) {
      //   this.$message({
      //     type: "error",
      //     message: "至少选择一个物料！",
      //   });
      //   return;
      // }
      //判断选中的物料的需求是不是null或0或undefined
      // this.tableDatajihuaXZ.forEach(item =>{
      //   console.log(item.demandNum)
      //   if(item.demandNum <1 ||item.demandNum==null||item.demandNum ==undefined){
      //     this.$message({
      //     type: "error",
      //     message: "所选物料需求数不能为空",
      //   });
      //   return;
      //   }else {
      //     console.log(789)
      //   }
      // })
      // for(var id = 0;id<this.tableDatajihuaXZ.length;id++) {
      //   if(this.tableDatajihuaXZ[id].demandNum ==undefined||this.tableDatajihuaXZ[id].demandNum==null||this.tableDatajihuaXZ[id].demandNum<1) {
      //     this.$message({
      //     type: "error",
      //     message: "所选物料需求数不能为空",
      //   });
      //   return
      //   }
      // }

      for (var i = 0; i < this.tableDatajihua.length; i++) {
        this.tableDatajihua[i].suId = this.tableDatajihua[i].id;
        delete this.tableDatajihua[i].id;
      }
      for (let index = 0; index < this.tableDatajihua.length; index++) {
        if(this.tableDatajihua[index].demandNum<=0) {
          this.$message({
            type:'warning',
            message:'请填写正确的需求数'
          })
          return
        }
      }
      console.log(this.tableDatajihua);
      var obj = {};
      obj.wzDemandPlanInfos = this.tableDatajihua;
      obj.pickName = this.queryParams.pickName;
      obj.useing = this.queryParams.useing;
      obj.planMonth = this.queryParams.planMonth;
      obj.planType = this.queryParams.planType;
      obj.note = this.queryParams.note;
      obj.id = this.queryParams.id;
      obj.moneySource = this.queryParams.moneySource;
      request({
        url: "/system/demandPlan",
        method: this.leixng,
        data: obj,
      }).then((response) => {
        this.$message({
          type: "success",
          message: "操作成功!",
        });
       this.goback()
      });
    },
  },
};
</script>
<style >
.shenqing {
  color: #05a380;
  font-weight: 700;
  margin-left: 15px;
}
.inputme {
  /* width: 1346px; */
  height:57px;
  overflow: hidden;
  /* overflow-x: scroll;
  overflow-y: hidden;
  position: relative; */
}
.inputme input {
  height: 57px;
  float: left;
  font-size: 14px;
  color: #606266;
  border: 1px solid #dfe6ec;
  box-sizing: border-box;
  background-color: #fff;
  /* border-bottom: 1px solid #dfe6ec; */
}
</style>

